package net.xdclass.online_xdclass.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import net.xdclass.online_xdclass.model.entity.User;
import net.xdclass.online_xdclass.model.request.LoginRequest;
import net.xdclass.online_xdclass.model.request.RegisterRequest;
import net.xdclass.online_xdclass.service.UserService;
import net.xdclass.online_xdclass.utils.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Log4j2
@Api(tags = "用户模块")
@RestController
@RequestMapping("api/v1/pri/user")
public class UserController {


    @Autowired
    private UserService userService;

    /**
     * 注册接口
     *
     * @param request
     * @return
     */
    @PostMapping("register")
    public JsonData register(@RequestBody RegisterRequest request) {
        log.info("UserController -- > 开始进行进行注册{}", request);
        int rows = userService.register(request);
        if (rows == -2) {
            return JsonData.buildError("该手机号已注册，请重试");
        }
        return rows == 1 ? JsonData.buildSuccess() : JsonData.buildError("注册失败，请重试");

    }


    /**
     * 登录接口
     *
     * @param loginRequest
     * @return
     */
    @PostMapping("login")
    public JsonData login(@RequestBody LoginRequest loginRequest) {

        String token = userService.verifyLogin(loginRequest.getPhone(), loginRequest.getPwd());

        return token == null ? JsonData.buildError("登录失败，账号或密码错误") : JsonData.buildSuccess(token);

    }


    /**
     * 根据用户id查询用户信息
     *
     * @param request
     * @return
     */
    @GetMapping("getUserInfo")
    public JsonData getUserInfo(HttpServletRequest request) {
        String userId = (String) request.getAttribute("user_id");
        if (userId == null) {
            log.info("未获取到userId");
            return JsonData.buildError("未获取到userId");
        }
        User user = userService.findByUserId(userId);
        log.info("获取用户信息 [{}]", user);
        return JsonData.buildSuccess(user);
    }


}
